/*******************************************************************************
 * Copyright (c) 2011, 2012 Mia-Software.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Herve ESTEGUET (Mia-Software) - Bug 381352 - [Releng] There must be a project to configure the build by tycho
 *******************************************************************************/
package org.eclipse.releng.tycho.util;

import java.io.File;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class RelativePathTask extends Task {

	private String property;
	private File basedir;
	private File dir;
	
	@Override
	public void execute() throws BuildException {
		if (property == null || property.trim().isEmpty()) {
			throw new BuildException("The property attribute is required.", getLocation());
		}
		if (basedir == null) {
			throw new BuildException("The parent property is required.", getLocation());
		}
		if (dir == null) {
			throw new BuildException("The child property is required");
		}
		String result = relativePath(basedir.getAbsolutePath(), dir.getAbsolutePath());
		getProject().setProperty(property, result);
		log(String.format("The path of '%s' relatively to '%s' is '%s'", dir, basedir, result));
	}

	public void setProperty(String aPropertyName) {
		this.property = aPropertyName;
	}
	
	public void setBasedir(File aDir) {
		this.basedir = aDir;
	}
	
	public void setDir(File aDir) {
		this.dir = aDir;
	}
	
	private String join(String[] strings, String glue, int from, int to) {
		String result = "";
		if (from < strings.length) {
			result = strings[from];
			for (int i = from + 1; i < to && i < strings.length ; i++) {
				result +=  glue + strings[i];
			}
		}
		return result;
	}
	
	private String relativePath(String first, String second) {
		String[] firstPath = first.split("[\\/]");
		String[] secondPath = second.split("[\\/]");
		int i = 0;
		for(; i < firstPath.length && i < secondPath.length && firstPath[i].equals(secondPath[i]); i++);
		String result = join(secondPath, "/", i, secondPath.length);
		if (firstPath.length > secondPath.length) {
			for (; i < firstPath.length; i++) result = "../" + result;
		}
		return result;
	}
	
}
